import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

import Layout from '@/layout'

export const constantRoutes = [
  {
    path: '/login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/login/register',
    component: () => import('@/views/login/register'),
    hidden: true
  },

  {
    path: '/404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    component: Layout,
    redirect: '/dashboard',
    children: [{
      path: 'dashboard',
      name: 'Dashboard',
      component: () => import('@/views/dashboard/index'),
      meta: { title: '首页', icon: 'dashboard' }
    }]
  },

  {
    path: '/example',
    component: Layout,
    redirect: '/example',
    name: 'Example',
    meta: { title: '班级学员管理', icon: 'el-icon-s-help' },
    children: [
      {
        path: 'classes',
        name: 'Classes',
        component: () => import('@/views/classes'),
        meta: { title: '班级管理', icon: 'el-icon-menu' }
      },
      {
        path: 'student',
        name: 'Student',
        component: () => import('@/views/student'),
        meta: { title: '学员管理', icon: 'el-icon-user-solid' }
      }
    ]
  },
  {
    path: '/system',
    component: Layout,
    redirect: '/system',
    name: 'System',
    meta: { title: '系统信息管理', icon: 'el-icon-s-tools' },
    children: [
      {
        path: 'dept',
        name: 'Dept',
        component: () => import('@/views/dept'),
        meta: { title: '部门管理', icon: 'el-icon-menu' }
      },
      {
        path: 'emp',
        name: 'Emp',
        component: () => import('@/views/emp'),
        meta: { title: '员工管理', icon: 'el-icon-user-solid' }
      }
    ]
  },
  {
    path: '/report',
    component: Layout,
    redirect: '/report',
    name: 'Report',
    meta: { title: '数据统计管理', icon: 'el-icon-s-tools' },
    children: [
      {
        path: 'emp-report',
        name: 'emp-report',
        component: () => import('@/views/emp-report'),
        meta: { title: '员工信息统计', icon: 'el-icon-s-data' }
      },
      {
        path: 'student-report',
        name: 'student-report',
        component: () => import('@/views/student-report'),
        meta: { title: '学员信息统计', icon: 'el-icon-s-data' }
      }
    ]
  },
  {
    path: '/logs',
    component: Layout,
    redirect: '/logs',
    children: [{
      path: 'logs',
      name: 'Logs',
      component: () => import('@/views/logs'),
      meta: { title: '系统日志', icon: 'el-icon-document' }
    }]
  },
  {
    path: '/chat',
    component: Layout,
    redirect: '/chat',
    children: [{
      path: 'chat',
      name: 'Chat',
      component: () => import('@/views/chat'),
      meta: { title: 'Ai对话', icon: 'el-icon-document' }
    }]
  },
  // {
  //   path: '/message',
  //   component: Layout,
  //   redirect: '/message',
  //   children: [{
  //     path: 'message',
  //     name: 'message',
  //     component: () => import('@/views/message'),
  //     meta: { title: '通知', icon: 'el-icon-s-comment' }
  //   }]
  // },
  {
    path: '/announcement',
    component: Layout,
    redirect: '/announcement/view',
    name: 'Announcement',
    meta: { title: '公告管理', icon: 'el-icon-document' },
    children: [
      {
        path: 'publish',
        name: 'PublishAnnouncement',
        component: () => import('@/views/announcement/publish'),
        meta: { title: '发布公告', icon: 'el-icon-edit-outline', roles: ['role_admin', 'admin'] }
      },
      {
        path: 'view',
        name: 'ViewAnnouncement',
        component: () => import('@/views/announcement/view'),
        meta: { title: '查看公告', icon: 'el-icon-view' }
      },
      // {
      //   path: 'draft',
      //   name: 'DraftBox',
      //   component: () => import('@/views/announcement/draft'),
      //   meta: { title: '草稿箱', icon: 'el-icon-receiving', roles: ['role_admin', 'admin'] }
      // }
    ]
  },
  // 404 page must be placed at the end !!!
  { path: '*', redirect: '/404', hidden: true }
]

const createRouter = () => new Router({
  // mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  routes: constantRoutes
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

// 全局前置守卫，根据用户角色控制页面访问权限
import store from '@/store'
import { getToken } from '@/utils/auth'
import { Message } from 'element-ui'

router.beforeEach(async(to, from, next) => {
  console.log('路由守卫 - 访问路径:', to.path)
  
  // 判断是否需要登录权限
  if (to.path === '/login' || to.path === '/login/register') {
    console.log('登录页面，直接放行')
    next()
  } else {
    // 判断是否已登录
    const hasToken = getToken()
    console.log('当前Token状态:', hasToken ? '已登录' : '未登录')
    
    if (!hasToken) {
      console.log('未登录，重定向到登录页')
      next('/login')
    } else {
      // 判断是否有访问权限
      const roles = store.getters.roles
      console.log('当前用户角色:', roles)
      
      // 如果页面需要特定角色
      if (to.meta && to.meta.roles) {
        console.log('当前页面需要角色权限:', to.meta.roles)
        // 更灵活的角色匹配逻辑
        const hasPermission = roles.some(userRole => {
          // 用户角色可能带有或不带有前缀'role_'
          const normalizedUserRole = userRole.toLowerCase().replace('role_', '')
          
          return to.meta.roles.some(routeRole => {
            // 路由角色可能带有或不带有前缀'role_'
            const normalizedRouteRole = routeRole.toLowerCase().replace('role_', '')
            return normalizedUserRole === normalizedRouteRole
          })
        })
        
        console.log('用户是否有权限:', hasPermission)
        
        if (hasPermission) {
          console.log('权限验证通过，允许访问')
          next()
        } else {
          console.log('权限验证失败，重定向到首页')
          Message.warning('您没有权限访问该页面')
          next('/dashboard')
        }
      } else {
        // 不需要特定角色的页面，所有已登录用户都可访问
        console.log('页面无需特定权限，允许访问')
        next()
      }
    }
  }
})

export default router
